const jwt = require('jwt-simple');
const appConfig=require('../config/config')
const {UserLoginExpiredError,UserAuthError}=require('../commonError/UserError')
const {responsError}=require('../utils/responseUtil')
const {queryMysql}=require('../utils/queryMysqlUtil')

module.exports =async function(req, res, next) {
	const token=req.headers['authorization']
    const {secret}=appConfig.chihiroUser
	if (token) {
		try {
			const decoded = jwt.decode(token, secret);
            // console.log(decoded)
			//验证登录是否过期
			if (decoded.exp <= Date.now()) {
                responsError(res,new UserLoginExpiredError())
				return
			}else{
				//未过期，验证用户是否存在
				const queryStr=`select * from chihiro_users where id=${decoded.iss}`
                let { results }=await queryMysql(queryStr).catch((err)=>{
                    return Promise.reject(err)
                })
                if(results.length===0){
                    responsError(res,new UserAuthError())
                    return
                }else{
                    //验证存在
                    global.cur_login_user_id=decoded.iss
                    next()
                }
			}

		} catch (err) {
            responsError(res,new UserAuthError())
			return
		}
	} else {
		//在前台写了vue导航卫士，如果发现没有token自己前台就会重定向，不用后台管
        responsError(res,new UserAuthError())
		return
	}
};
